<?php
declare(strict_types=1);

namespace App\Wxc\Controller\SharerMp\V1;

use App\Wxc\Request\SharerMp\V1\GetProductListRequest;
use App\Wxc\Service\Query\ProductQuery;
use App\Wxc\Service\WxcProductService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Mine\Middlewares\CheckModuleMiddleware;
use Mine\MineController;
use Psr\Http\Message\ResponseInterface;

/**
 * 商品接口
 */
#[Controller(prefix: "wxc/sharer-mp/v1/product")]
#[Middleware(middleware: CheckModuleMiddleware::class)]
class ProductController extends MineController
{

    #[Inject]
    protected WxcProductService $productService;

    /**
     * 获取商品列表
     */
    #[GetMapping('list')]
    public function getProductList(): ResponseInterface
    {
        $req = GetProductListRequest::validateAndCreate($this->request->all());
        $getList = ProductQuery::from($req);
        if (is_string($req->keywords) && $req->keywords) {
            $getList->search([
                'title' => $req->keywords,
            ]);
        }

        $getList->withRelation(['spec']);

        // 商品主表查询
        $query = $this->productService->getQuery($getList);
        // 联合商品副表查询，仅返回开启了佣金的商品
        $query->whereHas('spec', function ($query) {
            $query->where('use_commission', 1);
        });

        $result = $this->productService->queryCursorPagination('product_id', $query, $req->next_key, $req->page_size);

        // todo delete 复制一些list元素，用来测试
        for ($i = 1; $i < 10; $i++) {
            $result['list'][] = $result['list'][0];
        }

        return $this->success('ok', $result);
    }
}
